package org.buptsse.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;

import org.buptsse.entity.User;
import org.buptsse.page.MyInfoPage;
import org.buptsse.page.MyPasswordPage;
import org.buptsse.page.MyPhotoPage;
import org.buptsse.thread.UpdateUserPhotoThread;
import org.buptsse.utils.APPConstant;
import org.buptsse.utils.GloableInstance;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

public class MySettingActivity extends Activity implements OnClickListener {
	
	private Handler handler=new Handler()
	{

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			if(pDialog!=null)
				pDialog.dismiss();
			switch (msg.what) {
			case APPConstant.NetUnavailable:
				Toast.makeText(getApplicationContext(), "网络连接不可用", 1000).show();
				break;

			case APPConstant.getUserDataError:
				Toast.makeText(getApplicationContext(), "获取用户信息失败", 1000).show();
				break;
			case APPConstant.NewPasswordNotSame:
				Toast.makeText(getApplicationContext(), "输入的密码不一致", 1000).show();
				break;
			case APPConstant.ChangePasswordError:
				Toast.makeText(getApplicationContext(), "修改密码失败", 1000).show();
				break;
			case APPConstant.ChangePasswordFinish:
				myPasswordPage.clearPwd();
				Toast.makeText(getApplicationContext(), "修改成功", 1000).show();
				break;
			case APPConstant.getUserDataFinish:
				myInfoPage.FillUserInfo();
				myPhotoPage.setPhoto();
				break;
			case APPConstant.UploadPhotoFinish:
				//上传照片成功
				Toast.makeText(getApplicationContext(), "操作成功", 1000).show();
				break;
			case APPConstant.UploadPhotoError:
				//上传照片失败
				Toast.makeText(getApplicationContext(), "操作失败", 1000).show();
				myPhotoPage.resetPhoto();
				break;
			case APPConstant.showWaittingDialog:
				ShowWaittingDialog((String)msg.obj);
				break;
			}
			super.handleMessage(msg);
		}
		
	};
	
	/** Called when the activity is first created. */
	private ViewPager viewPager = null;
	private User user = null;
	
	private MyPasswordPage myPasswordPage = null;
	private MyInfoPage myInfoPage = null;
	private MyPhotoPage myPhotoPage = null;
	private Button updateButton;
	private static final int InfoPage=0,PhotoPage=1,PasswordPage=2;
	private int currentPage=InfoPage;
	private RadioButton infoRB,photoRB,pwdRB;
	private Button backButton = null;
	private ProgressDialog pDialog;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lmy_profile);
		
		myPasswordPage = new MyPasswordPage(this, user,handler);
		myInfoPage = new MyInfoPage(this, user);
		myPhotoPage = new MyPhotoPage(this, this);
		
		backButton = (Button) this.findViewById(R.id.bt_back);
		backButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				/*Intent it = new Intent();
				it.putExtra("user", user);
				MySettingActivity.this.setResult(RESULT_OK, it);*/
				MySettingActivity.this.finish();
			}
		});

		infoRB=(RadioButton) findViewById(R.id.rd_info);
		photoRB=(RadioButton) findViewById(R.id.rd_photo);
		pwdRB=(RadioButton) findViewById(R.id.rd_pwd);

		viewPager = (ViewPager) findViewById(R.id.viewPager);
		MyPagerAdapter adapter = new MyPagerAdapter(this);
		viewPager.setAdapter(adapter);
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int page) {
				if(page==0)
				{
					currentPage=InfoPage;
					infoRB.setChecked(true);
				}
				else if(page==1)
				{
					currentPage=PhotoPage;
					photoRB.setChecked(true);
				}
				else if(page==2)
				{
					currentPage=PasswordPage;
					pwdRB.setChecked(true);
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});

		RadioGroup radioGroup = (RadioGroup) this
				.findViewById(R.id.rg_search_result_btns);
		// here is the tab to be ture
		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.rd_info:
					viewPager.setCurrentItem(0);
					break;
				case R.id.rd_photo:
					viewPager.setCurrentItem(1);
					break;
				case R.id.rd_pwd:
					viewPager.setCurrentItem(2);
					break;
				default:
					break;
				}
			}
		});
		
		//刷新按钮
		updateButton=(Button) findViewById(R.id.update_button);
		updateButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ShowWaittingDialog("正在加载信息");
				myInfoPage.updateUserData();
			}
		});
		
		//刷新用户信息
		ShowWaittingDialog("正在加载信息");
		myInfoPage.UpdateUserData(this, handler);
	}

	public void ShowWaittingDialog(String msg)
	{
		pDialog=new ProgressDialog(this);
		pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setMessage(msg); 
        pDialog.show(); 
	}
	
	private class MyPagerAdapter extends PagerAdapter {

		private ArrayList<LinearLayout> views;

		public MyPagerAdapter(Context context) {
			views = new ArrayList<LinearLayout>();
			views.add(myInfoPage);
			views.add(myPhotoPage);
			views.add(myPasswordPage);
		}

		@Override
		public void destroyItem(View view, int arg1, Object object) {
			((ViewPager) view).removeView((LinearLayout) object);
		}

		@Override
		public void finishUpdate(View arg0) {

		}

		@Override
		public int getCount() {
			return views.size();
		}

		@Override
		public Object instantiateItem(View view, int position) {
			View myView = views.get(position);
			((ViewPager) view).addView(myView);
			return myView;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

	}

	@Override
	public void onClick(View v) {
		int vid = v.getId();
		switch (vid) {

		}
	}
	
	String[] type={"拍照","从文件中选择"};
	final int TAKE_PHOTO_WITH_DATA=1;
	final int TAKE_PHOTO_FROM_FILE=2; 
	final int PHOTO_CROP_FINISH=3;
	final int GET_ISBN=4;
	
	public void ChooseImage()
	{
		new AlertDialog.Builder(this).setTitle("选择照片")
		.setItems(type, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				switch (which) {
				case 0:
					//拍照
					Intent intent = new Intent(  
                            MediaStore.ACTION_IMAGE_CAPTURE);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri  
                            .fromFile(new File(Environment  
                                    .getExternalStorageDirectory(),  
                                    "cloudLearning_temp.jpg")));
					startActivityForResult(intent, TAKE_PHOTO_WITH_DATA);
					break;

				case 1:
					//从文件选择
					Intent intent2 = new Intent(Intent.ACTION_PICK, null);  
	                /* 开启Pictures画面Type设定为image */    
					intent2.setDataAndType(  
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,  
                            "image/*");  
	                startActivityForResult(intent2, TAKE_PHOTO_FROM_FILE);
					break;
				}
			}
		}).create().show();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		
		if(resultCode!=RESULT_OK)
            return;
		switch (requestCode) {
		case TAKE_PHOTO_WITH_DATA:
			File temp = new File(Environment.getExternalStorageDirectory()  
                    + "/cloudLearning_temp.jpg");  
            startPhotoZoom(Uri.fromFile(temp));
			break;/*
			if(data==null || data.getExtras()!=null)
				break;
			Bitmap photo = (Bitmap) data.getExtras().get("data");
			if(photo!=null){
				myPhotoPage.setNewPhoto(photo);
				//上传
        		UpdateUserPhotoThread uupt=new UpdateUserPhotoThread(this, handler,GloableInstance.user.getName(), GloableInstance.user.getPassword(), photo);
        		uupt.start();
        		ShowWaittingDialog("正在上传");
			}
			break;*/

		case TAKE_PHOTO_FROM_FILE:
			startPhotoZoom(data.getData());
			/*Uri uri = data.getData();    
            ContentResolver cr = this.getContentResolver();    
            try {    
                Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));    
                if(bitmap!=null)
                {
                	myPhotoPage.setNewPhoto(bitmap);
                	//上传
            		UpdateUserPhotoThread uupt=new UpdateUserPhotoThread(this, handler,GloableInstance.user.getName(), GloableInstance.user.getPassword(), bitmap);
            		uupt.start();
            		ShowWaittingDialog("正在上传");
                }
            } catch (FileNotFoundException e) {    
                //Log.e("Exception", e.getMessage(),e);    
            }   */
			break;
		case PHOTO_CROP_FINISH:
			Bitmap photoCroped = (Bitmap) data.getExtras().get("data");
			//Toast.makeText(getApplicationContext(), "ddd"+photoCroped, 1000).show();
			if(photoCroped!=null){
				myPhotoPage.setNewPhoto(photoCroped);
				UpdateUserPhotoThread uupt=new UpdateUserPhotoThread(this, handler,GloableInstance.user.getName(), GloableInstance.user.getPassword(), photoCroped);
        		uupt.start();
        		ShowWaittingDialog("正在上传");
				//book.setBitmap(photoCroped);
				//bookImage.setImageBitmap(photoCroped);
				//getPhoto=true;
			}
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	public void startPhotoZoom(Uri uri) {  
        /*  
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页  
         * yourself_sdk_path/docs/reference/android/content/Intent.html  
         * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能,  
         * 是直接调本地库的，小马不懂C C++  这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么  
         * 制做的了...吼吼  
         */ 
        Intent intent = new Intent("com.android.camera.action.CROP");  
        intent.setDataAndType(uri, "image/*");  
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪  
        intent.putExtra("crop", "true");  
        // aspectX aspectY 是宽高的比例  
        intent.putExtra("aspectX", 1);  
        intent.putExtra("aspectY", 1);  
        // outputX outputY 是裁剪图片宽高  
        intent.putExtra("outputX", 150);  
        intent.putExtra("outputY", 150);  
        intent.putExtra("return-data", true);  
        startActivityForResult(intent, PHOTO_CROP_FINISH);  
    }  
}